<div class="mdui-toolbar">
    <button class="mdui-btn mdui-btn-icon" mdui-menu="{target: '#filter-menu'}" id="filter-button"
        mdui-tooltip="{content: '筛选'}">
        <i class="mdui-icon material-icons">filter_list</i>
    </button>
    <div class="mdui-menu" id="filter-menu" style="transform-origin: 100% 0px; position: fixed;">
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">用户 ID</label>
            <input class="mdui-textfield-input" type="text" id='where_id' />
        </div>
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">用户昵称</label>
            <input class="mdui-textfield-input" type="text" id='where_name' />
        </div>
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">用户邮箱</label>
            <input class="mdui-textfield-input" type="text" id='where_email' />
        </div>
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">用户编程猫ID</label>
            <input class="mdui-textfield-input" type="text" id='where_bcm_id' />
        </div>
    </div>
    <select class="mdui-select" id="sort-select" mdui-select="{position: 'bottom'}">
        <option value="id,0">用户 ID ↑</option>
        <option value="id,1" selected>用户 ID ↓</option>
        <option value="name,0">用户昵称 ↑</option>
        <option value="name,1">用户昵称 ↓</option>
    </select>
    <div class="mdui-toolbar-spacer"></div>
    <button class="mdui-btn mdui-btn-icon" id="update" mdui-tooltip="{content: '刷新'}">
        <i class="mdui-icon material-icons">refresh</i>
    </button>
</div>
<div id="table"></div>
<div class="mdui-btn-group pages"></div>
<style>
    .ds-table {
        height: calc(100% - 57px - 57px);
        border-top: 1px solid rgba(0, 0, 0, .12);
        border-bottom: 1px solid rgba(0, 0, 0, .12);
    }
</style>
<script>
    !function () {
        var $ = mdui.$;
        var tb = new table.T($("#table"));

        tb.addField("#");
        tb.addField("用户");
        tb.addField("邮箱");
        tb.addField("编程猫ID");
        tb.addField("注册时间");
        tb.addField("操作");

        var loading = false; // 加载中

        var page = 1; // 当前页
        var size = 1; // 总页数

        var sort_field = 'id'; // 进行排序的字段
        var sort_type = '1'; // 排序方式：0升序1降序

        var where_id = ''; // 筛选数据：用户id
        var where_name = ''; // 筛选数据：用户昵称
        var where_email = ''; // 筛选数据：用户邮箱
        var where_bcm_id = ''; // 筛选数据：编程猫ID

        $('#update').on('click', update);
        $('#sort-select').on('change', () => {
            var v = $('#sort-select').val();
            sort_field = v.split(',')[0];
            sort_type = v.split(',')[1];
            page = 1;
            update();
        });
        $('#where_id').on('change', () => {
            where_id = $('#where_id').val();
            page = 1;
            update();
        });
        $('#where_name').on('change', () => {
            where_name = $('#where_name').val();
            page = 1;
            update();
        })
        $('#where_email').on('change', () => {
            where_email = $('#where_email').val();
            page = 1;
            update();
        })
        $('#where_bcm_id').on('change', () => {
            where_bcm_id = $('#where_bcm_id').val();
            page = 1;
            update();
        })

        tb.on('cellClick', function ({ row, line }) {
            if (line == 5) return;
            userDetailed(tb.getCell(row, 0));
        });

        function isFilter() {
            return where_id || where_name || where_email || where_bcm_id;
        }

        function update() {
            if (loading) return;
            loading = true;

            $('#filter-button')[isFilter() ? 'addClass' : 'removeClass']('mdui-text-color-theme')

            renderPages();
            tb.clear();
            tb.startLoading();

            $.ajax({
                url: "./api/get_user_list?p=" + page +
                    '&sort_field=' + encodeURIComponent(sort_field) +
                    '&sort_type=' + encodeURIComponent(sort_type) +
                    '&where_id=' + encodeURIComponent(where_id) +
                    '&where_name=' + encodeURIComponent(where_name) +
                    '&where_email=' + encodeURIComponent(where_email) +
                    '&where_bcm_id=' + encodeURIComponent(where_bcm_id),
                dataType: "json",
                success: function (res) {
                    if (res.code == 200) {
                        tb.endLoading();
                        loading = false;

                        size = res.data.size;

                        if (size) {
                            $('.pages').show();
                            var data = res.data.data
                            for (let d of data) {
                                let name_ = $(`<div class="mdui-chip">
  <img class="mdui-chip-icon" src="avatar1.jpg"/>
  <span class="mdui-chip-title">Example Chip</span>
</div>`);
                                name_.find('img').attr('src', d.img);
                                name_.find('span').text(d.name);

                                let newtab = $(`<a class="mdui-btn mdui-btn-icon" target="_blank" mdui-tooltip="{content: '在新标签页中打开'}"><i class="mdui-icon material-icons">open_in_new</i></a>`)
                                let change = $(`<button class="mdui-btn mdui-btn-icon" mdui-tooltip="{content: '更改'}"><i class="mdui-icon material-icons">create</i></button>`)
                                let ban = $(`<button class="mdui-btn mdui-btn-icon" mdui-tooltip="{content: '冻结'}"><i class="mdui-icon material-icons">block</i></button>`)

                                newtab.attr('href', '/user/' + d.id);

                                change.on('click', function () {
                                    changePage(d.id);
                                })

                                ban.on('click', function () {
                                    banPage(d.id)
                                })

                                tb.addRow([
                                    d.id, {
                                        type: "el",
                                        el: name_
                                    },
                                    d.email,
                                    d.bcm_id,
                                    new Date(d.time * 1000).toLocaleString(),
                                    {
                                        type: 'el',
                                        el: $('<div></div>').append(newtab).append(change).append(ban)
                                    }
                                ]);
                            }
                        } else {
                            $('.pages').hide();
                        }
                        renderPages();
                    }
                    else {
                        mdui.snackbar(res.msg || "加载失败")
                    }
                }
            });
        }

        function renderPages() {
            $(".pages").html('');
            var omit = true; // 是否省略

            // 添加向左翻页按钮
            var left = $(`<button class="mdui-btn left">&lt;</button>`)
            left.appendTo($(".pages"));

            for (let i = 0; i < size; i++) {
                let toadd = false; // 是否要添加页数按钮

                if (i === 0) toadd = true; // 第一页要添加
                if (i === size - 1) toadd = true; // 最后一页要添加
                if (i - page < 2 && i - page > -4) toadd = true; // 如果与当前页的距离小于2，则添加
                if (page < 5 && i < 7) toadd = true; // 如果当前页小于5，则前7页都要添加
                if (page > size - 5 && i > size - 7) toadd = true; // 如果当前页在倒数5页范围内，则倒数7页都要添加

                if (toadd) {
                    // 渲染页数按钮
                    let button = $(`<button class="mdui-btn ${(i + 1) == page ? `mdui-btn-active` : ""} page-num">${i + 1}</button>`);
                    button.on("click", () => { // 点击事件
                        page = Number(i + 1);
                        update();
                    })
                    button.appendTo($(".pages"));
                    omit = true;
                } else {
                    if (omit) {
                        $(`<button class="mdui-btn" disabled>...</button>`).appendTo($(".pages"));
                        omit = false;
                    }
                }
            }

            // 添加向右翻页按钮
            var right = $(`<button class="mdui-btn right">&gt;</button>`)
            right.appendTo($(".pages"));

            // 根据条件禁用按钮
            left.prop("disabled", page === 1);
            right.prop("disabled", page === size)

            // 添加点击事件
            left.on("click", () => { // 向左
                page -= 1
                update();
            })

            right.on("click", () => { // 向右
                page += 1
                update();
            })
        }

        function userDetailed(id) {
            const dialog = $.dialog({
                history: false,
                cssClass: "ds-user-detailed ds-loadable",
                content: `
<div class="mdui-list-item mdui-p-l-0">
    <div class="mdui-list-item-avatar">
        <img src="" id='ds-ud-img'>
    </div>
    <div class="mdui-list-item-content" id='ds-ud-name'></div>
</div>

<p class='mdui-typo-subheading'>基本信息</p>
<table class="mdui-table mdui-shadow-0" id='ds-ud-basic'></table>

<p class='mdui-typo-subheading'>活跃信息</p>
<div class="ds-ud-activity"></div>

<p class='mdui-typo-subheading'>注册信息</p>
<table class="mdui-table mdui-shadow-0" id='ds-ud-register'></table>

<p class='mdui-typo-subheading'>最后登录信息</p>
<table class="mdui-table mdui-shadow-0" id='ds-ud-last'></table>

<div class="mdui-spinner"></div>
`
            });

            const content = dialog.$element

            window.parent.mdui.mutation();

            $.ajax({
                url: "./api/get_user_data?id=" + id,
                dataType: "json",
                success: function (res) {
                    if (res.code != 200) {
                        dialog.close();
                        return mdui.snackbar(res.msg || "加载失败")
                    }

                    const data = res.data;

                    content.find('.mdui-spinner').remove();

                    // 用户头像和昵称
                    content.find('#ds-ud-img').attr('src', data.img);
                    content.find('#ds-ud-name').text(data.name);

                    // 信息表
                    const tableData = {
                        "#ds-ud-basic": [
                            ['用户 ID', data.id],
                            ['头像链接', data.img],
                            ['昵称', data.name],
                            ['邮箱', data.email],
                            ['编程猫ID', data.bcm_id],
                        ],
                        "#ds-ud-register": [
                            ['注册时间', new Date(data.time * 1000).toLocaleString()],
                            ['注册IP', data.ip],
                        ],
                        "#ds-ud-last": [
                            ['最后登录时间', data.last_time ? new Date(data.last_time * 1000).toLocaleString() : '无数据'],
                            ['最后登录 IP', data.last_ip || '无数据'],
                            ['最后登录 UA', data.ua || '无数据'],
                        ],
                    };


                    for (let k in tableData) {
                        let table = content.find(k);

                        for (let i = 0; i < tableData[k].length; i++) {
                            let tr = $(`<tr></tr>`);

                            for (let j = 0; j < tableData[k][i].length; j++) {
                                let td = $(`<td></td>`);

                                td.text(tableData[k][i][j]);
                                tr.append(td);
                            }

                            table.append(tr);
                        }
                    }

                    // 活跃度
                    const activity = content.find('.ds-ud-activity');

                    const activityData = [
                        [data.post_count, '发帖量'],
                        [data.talk_count, '评论量'],
                        [data.good_count, '点赞量'],
                        [data.get_good_count, '获赞量'],
                        [data.get_view_count, '获阅量'],
                    ];

                    for (let i = 0; i < activityData.length; i++) {
                        const item = $(`<div class="ds-ud-activity-item"></div>`);

                        $('<h3>').text(activityData[i][0]).appendTo(item);
                        $('<span>').text(activityData[i][1]).appendTo(item);

                        activity.append(item);
                    }

                    dialog.handleUpdate();
                }
            });
        }

        function change(id, name, img, email, bcm_id) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: "./api/change_user_data",
                    method: 'POST',
                    data: {
                        id: id,
                        name: name,
                        img: img,
                        email: email,
                        bcm_id: bcm_id,
                    },
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 200) {
                            resolve()
                        } else {
                            reject(res.msg)
                        }
                    },
                    error: function (res) {
                        reject(res.msg)
                    }
                });
            })
        };

        function changePage(id) {
            var saving = false;

            const dialog = $.dialog({
                history: false,
                cssClass: "ds-loadable",
                content: `<div class="mdui-textfield">
            <label class="mdui-textfield-label">头像链接</label>
            <input class="mdui-textfield-input" type="text" id='ds-change-img' maxlength="8182" required />
      <div class="mdui-textfield-error">头像链接不能为空</div>
        </div>
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">昵称</label>
            <input class="mdui-textfield-input" type="text" id='ds-change-name' maxlength="50" required />
      <div class="mdui-textfield-error">昵称不能为空</div>
        </div>
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">邮箱</label>
            <input class="mdui-textfield-input" type="email" id='ds-change-email' required />
      <div class="mdui-textfield-error">邮箱格式不正确</div>
        </div>
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">编程猫ID</label>
            <input class="mdui-textfield-input" type="number" id='ds-change-bcmid' />
        </div>
<div class="mdui-spinner"></div>`,
                buttons: [{
                    text: '取消',
                    close: false,
                    onClick() {
                        if (content.find('.mdui-spinner').length || saving) return false;
                        dialog.close();
                    }
                }, {
                    text: '保存',
                    close: false,
                    onClick: function () {
                        if (content.find('.mdui-spinner').length || saving) return false;
                        const img = content.find('#ds-change-img').val();
                        const name = content.find('#ds-change-name').val();
                        const email = content.find('#ds-change-email').val();
                        const bcm_id = content.find('#ds-change-bcmid').val();

                        content.find('input,a').attr('disabled', '');
                        saving = true;
                        change(id, name, img, email, bcm_id).then(() => {
                            dialog.close();
                            update();
                            saving = false;
                            return mdui.snackbar("修改成功")
                        }, (msg) => {
                            saving = false;
                            content.find('input,a').removeAttr('disabled');
                            return window.parent.mdui.snackbar(msg || "修改失败")
                        });
                    },
                }]
            });

            const content = dialog.$element

            window.parent.mdui.mutation();

            $.ajax({
                url: "./api/get_user_data?id=" + id,
                dataType: "json",
                success: function (res) {
                    if (res.code != 200) {
                        dialog.close();
                        return mdui.snackbar(res.msg || "加载失败")
                    }

                    content.find('.mdui-spinner').remove();

                    const data = res.data;
                    content.find('#ds-change-img').val(data.img);
                    content.find('#ds-change-name').val(data.name);
                    content.find('#ds-change-email').val(data.email);
                    content.find('#ds-change-bcmid').val(data.bcm_id);

                    dialog.handleUpdate();

                    window.parent.mdui.updateTextFields();
                }
            });
        }

        function banUser(id, time) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: "./api/ban_user",
                    method: 'POST',
                    data: {
                        id,
                        time
                    },
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 200) {
                            resolve()
                        } else {
                            reject(res.msg)
                        }
                    },
                    error: function (res) {
                        reject(res.msg)
                    }
                });
            })
        };

        function banPage(id) {
            var saving = false;

            const dialog = $.dialog({
                history: false,
                title: '冻结',
                content: `<div class="mdui-textfield mdui-textfield-floating-label">
  <label class="mdui-textfield-label">冻结时长(秒)；0为永久</label>
  <input class="mdui-textfield-input" id="time" type="number" value="0" min="0"/>
</div>`,
                buttons: [{
                    text: '取消',
                    close: false,
                    onClick() {
                        if (saving) return false;
                        dialog.close();
                    }
                }, {
                    text: '解冻',
                    close: false,
                    onClick: function () {
                        if (saving) return false;
                        content.find('input,a').attr('disabled', '');
                        saving = true;
                        banUser(id, -1).then(() => {
                            dialog.close();
                            saving = false;
                            return mdui.snackbar("解冻成功")
                        }, (msg) => {
                            saving = false;
                            content.find('input,a').removeAttr('disabled');
                            return window.parent.mdui.snackbar(msg || "解冻失败")
                        });
                    },
                }, {
                    text: '冻结',
                    close: false,
                    onClick: function () {
                        if (saving) return false;
                        const time = content.find('#time').val();

                        if (!time || Number(time) < 0) {
                            return window.parent.mdui.snackbar("请正确输入时长")
                        }

                        content.find('input,a').attr('disabled', '');
                        saving = true;
                        banUser(id, time).then(() => {
                            dialog.close();
                            saving = false;
                            return mdui.snackbar("冻结成功")
                        }, (msg) => {
                            saving = false;
                            content.find('input,a').removeAttr('disabled');
                            return window.parent.mdui.snackbar(msg || "冻结失败")
                        });
                    },
                }]
            });

            const content = dialog.$element;
            
            dialog.handleUpdate();

            window.parent.mdui.updateTextFields();
        }

        update();
    }();
</script>